package com.mo2323.merchant.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mo2323.common.VO;
import com.mo2323.common.util.AjaxObject;
import com.mo2323.merchant.secruity.auth.AuthService;
import com.mo2323.service.merchant.IUserAuthService;
import com.mo2323.service.merchant.IWxAppletMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 高岐
 * @date 2019-02-12.
 */
@Controller
@RequestMapping("/auth")
public class UserAuthController extends BaseController {
    @Reference(timeout = 5000, version = "11")
    private IUserAuthService userAuthService;
    @Reference
    private IWxAppletMessageService wxAppletMessageService;
    @Autowired
    private AuthService authService;

    private static final String FORM_ID_SOURCE = "商户微信登录";

    @RequestMapping(value = "/checkUserAuthState", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxObject checkUserAuthState(@RequestParam String js_code,
                                         @RequestParam String encryptedData,
                                         @RequestParam String iv,
                                         @RequestParam String formID) {
        try {
            VO userInfoVO = userAuthService.getUserInfo(js_code, encryptedData, iv);
            String openID = userInfoVO.getString(IUserAuthService.USER_INFO_OPENID);
            String unionID = userInfoVO.getString(IUserAuthService.USER_INFO_UNIONID);
            String nickName = userInfoVO.getString(IUserAuthService.USER_INFO_NICKNAME);
            String avatarUrl = userInfoVO.getString(IUserAuthService.USER_INFO_AVATARURL);
            if (unionID == null || unionID.equals("") || unionID.length() < 5) {
                throw new Exception("错误的unionID：" + unionID);
            }
            wxAppletMessageService.saveFormIDToDB(formID, openID, FORM_ID_SOURCE);
            VO authStateVO = userAuthService.getUserAuthInfo(unionID, openID, nickName, avatarUrl);

            VO retVO = getUserAuthStateVO(authStateVO, unionID);
            return AjaxObject.ok().put("data", retVO.toHashMap(true));
        } catch (Exception e) {
            return AjaxObject.error(e.getMessage());
        }
    }

    private VO getUserAuthStateVO(VO authStateVO, String unionID) throws Exception {
        int authState = authStateVO.getInt("state");
        VO retVO = new VO();
        retVO.set("auth_state", authState);
        retVO.set("nickName", authStateVO.getString("nick_name"));
        retVO.set("avatarUrl", authStateVO.getString("avatar_url"));
        retVO.set("authStateInfo", authStateVO.toHashMap(true));
        if (authState == IUserAuthService.USER_AUTH_STATE_NONE) {

        } else if (authState == IUserAuthService.USER_AUTH_STATE_INVITED) {

        } else if (authState == IUserAuthService.USER_AUTH_STATE_AUTHORIZED) {

            retVO.set("authStateInfo", authStateVO.toHashMap(true));
            final String token = authService.wxAppletLogin(unionID);
            retVO.set("token", token);
        } else {
            throw new Exception("未定义的authState：" + authState);
        }
        return retVO;
    }

    @RequestMapping(value = "/checkInviteCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxObject checkInviteCode(@RequestParam String js_code,
                                      @RequestParam String encryptedData,
                                      @RequestParam String iv,
                                      @RequestParam String invite_code,
                                      @RequestParam String formId) {
        try {
            VO userInfoVO = userAuthService.getUserPhoneInfo(js_code, encryptedData, iv);
            String openID = userInfoVO.getString(IUserAuthService.USER_INFO_OPENID);
            String unionID = userInfoVO.getString(IUserAuthService.USER_INFO_UNIONID);
            String phoneNumber = userInfoVO.getString(IUserAuthService.USER_INFO_PHONE);
            wxAppletMessageService.saveFormIDToDB(formId, openID, FORM_ID_SOURCE);
            VO inviteInfoVO = userAuthService.checkInviteCode(invite_code, unionID, openID, phoneNumber);
            VO authStateVO = userAuthService.getUserAuthInfo(unionID);
            VO retVO = getUserAuthStateVO(authStateVO, unionID);
            return AjaxObject.ok().put("data", retVO.toHashMap(true));
        } catch (Exception e) {
            return AjaxObject.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/refreshUserAuthState", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxObject refreshUserAuthState(@RequestParam String js_code) {
        try {
            VO userInfoVO = userAuthService.getUserInfo(js_code);
            String openID = userInfoVO.getString(IUserAuthService.USER_INFO_OPENID);
            String unionID = userInfoVO.getString(IUserAuthService.USER_INFO_UNIONID);
            VO authStateVO = userAuthService.getUserAuthInfo(unionID);
            VO retVO = getUserAuthStateVO(authStateVO, unionID);
            return AjaxObject.ok().put("data", retVO.toHashMap(true));
        } catch (Exception e) {
            return AjaxObject.error(e.getMessage());
        }
    }

}
